import { createContext, Dispatch, SetStateAction, useContext, useEffect, useMemo, useState } from 'react';
import { Pressable, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated';
import { Shadow } from 'react-native-shadow-2';

export interface DropdownMenuOptions {
  label: string;
  value: number | string;
  disabled?: boolean;
}

type DropdownMenuContextType = {
  open: boolean;
  setOpen: Dispatch<SetStateAction<boolean>>;
  setOptions: Dispatch<SetStateAction<DropdownMenuOptions[]>>;
  setItemHeight: Dispatch<SetStateAction<number>>;
  setPosition: Dispatch<SetStateAction<{ x: number; y: number }>>;
};

const DropdownMenuContext = createContext<DropdownMenuContextType | null>(null);

export const useDropdownMenu = () => {
  const context = useContext(DropdownMenuContext);
  if (!context) {
    throw new Error('useDropdownMenu must be used within a DropdownMenuProvider');
  }
  return context;
};

export const DropdownMenuProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
  // 获取屏幕上的位置
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [open, setOpen] = useState(false);
  const [options, setOptions] = useState<DropdownMenuOptions[]>([]);
  const [ItemHeight, setItemHeight] = useState(44);
  const dropdownHeight = useSharedValue(0); // 初始高度为 0
  const backgroundZIndex = useSharedValue(0); // 初始高度为 0
  const handleToggleDropdown = () => {
    setOpen((prev) => !prev);
  };

  const handleCloseDropdown = () => {
    setOpen(false);
  };

  const height = useMemo(() => options.length * ItemHeight + 14, [ItemHeight, options.length]);

  const animatedStyle = useAnimatedStyle(() => ({
    height: dropdownHeight.value + 20,
  }));
  const animatedStyleWrapper = useAnimatedStyle(() => ({
    zIndex: dropdownHeight.value,
  }));

  useEffect(() => {
    if (open) {
      backgroundZIndex.value = withTiming(999, {}, (finished) => {
        if (finished) {
          dropdownHeight.value = withTiming(height, {
            duration: 500,
          });
        }
      });
    } else {
      dropdownHeight.value = withTiming(
        0,
        {
          duration: 500,
        },
        (finished) => {
          if (finished) {
            backgroundZIndex.value = withTiming(-1);
          }
        },
      );
    }

    // const value = open ? height : 0;
  }, [open, height, options]);

  return (
    <DropdownMenuContext.Provider
      value={{
        open,
        setOpen,
        setOptions,
        setItemHeight,
        setPosition,
      }}
    >
      <DropdownMenuContext.Consumer>
        {() => {
          return (
            <Animated.View style={[StyleSheet.absoluteFill, animatedStyleWrapper]}>
              <Pressable style={StyleSheet.absoluteFill} onPress={handleCloseDropdown}>
                <Animated.View
                  style={[
                    styles.dropdownContainer,
                    {
                      top: position.y + 22,
                      left: position.x - 144 / 2,
                    },
                    animatedStyle,
                  ]}
                >
                  <Shadow distance={5} startColor="rgba(0, 0, 0, 0.1)" style={styles.dropdown_wrapper_shadow}>
                    <View style={styles.dropdown_wrapper}>
                      {options.map((item, index) => (
                        <TouchableOpacity
                          key={index}
                          onPress={handleToggleDropdown}
                          style={[styles.dropdownItem, index === 0 && styles.no_border]}
                        >
                          <Text style={styles.dropdownText}>{item.label}</Text>
                        </TouchableOpacity>
                      ))}
                    </View>
                  </Shadow>
                </Animated.View>
              </Pressable>
            </Animated.View>
          );
        }}
      </DropdownMenuContext.Consumer>
      {children}
    </DropdownMenuContext.Provider>
  );
};

const styles = StyleSheet.create({
  dropdownContainer: {
    overflow: 'hidden',
    padding: 10,
  },
  dropdown_wrapper_shadow: {
    width: 140,
    borderRadius: 12,
    overflow: 'hidden',
    paddingHorizontal: 1,
  },
  dropdown_wrapper: {
    backgroundColor: '#fff',
    borderRadius: 12,
    overflow: 'hidden',
    justifyContent: 'center',
    alignItems: 'center',
  },
  dropdownItem: {
    width: '100%',
    height: 44,
    paddingVertical: 12,
    borderTopWidth: 0.2,
    borderTopColor: '#9D9D9D',
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
  },
  dropdownText: {
    fontSize: 15,
    lineHeight: 20,
    color: '#000',
  },
  no_border: {
    borderTopWidth: 0,
  },
});

export default DropdownMenuContext;
